﻿package net.wangit.framework.util;

import java.util.Iterator;
import java.util.Map;

import net.wangit.MapList;
import net.wangit.User;
import net.wangit.context.ActionContext;
import net.wangit.context.LocalContext;
import net.wangit.support.SqlProvider;
import net.wangit.user.privilege.DataPrivilege;
import net.wangit.user.privilege.DataPrivilegeFactory;
import net.wangit.util.StringUtil;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


public class DataPrivilegeUtil {

	private static final Log log = LogFactory
			.getLog(net.wangit.framework.util.DataPrivilegeUtil.class);

	public DataPrivilegeUtil() {
	}

	public static final String getUnitSql(String domain, String unitId,
			String sql) throws Exception {
		DataPrivilege dp = DataPrivilegeFactory.getUnitDataPrivilege(domain,
				unitId);
		return getSql(dp, sql);
	}

	public static final String getEnumerationSql(String domain, String eid,
			String sql) throws Exception {
		DataPrivilege dp = DataPrivilegeFactory.getEnumerationDataPrivilege(
				domain, eid);
		return getSql(dp, sql);
	}

	public static final void filterEnumeration(String domain, String eid,
			MapList list) {
		try {
			DataPrivilege dp = DataPrivilegeFactory
					.getEnumerationDataPrivilege(domain, eid);
			Map privileges = dp.getValuePrivileges();
			User user = LocalContext.getLocalContext().getActionContext()
					.getVisitor().getUser();
			for (Iterator keys = privileges.keySet().iterator(); keys.hasNext();) {
				Object key = keys.next();
				if (!user.hasDataPrivilege(key))
					list.removeRow("value", (String) privileges.get(key));
			}

		} catch (Exception exception) {
		}
	}

	private static final String getSql(DataPrivilege dp, String sql)
			throws Exception {
		if (dp == null)
			return sql;
		boolean hasPrivileges = false;
		ActionContext ac = LocalContext.getLocalContext().getActionContext();
		User user = ac.getVisitor().getUser();
		Map privileges = dp.getSqlPrivileges();
		StringBuffer conditions = new StringBuffer();
		for (Iterator keys = privileges.keySet().iterator(); keys.hasNext();) {
			Object key = keys.next();
			if (user.hasDataPrivilege(key)) {
				hasPrivileges = true;
				String dpSql = getDpSql(privileges.get(key), ac);
				conditions.append(" or (").append(dpSql).append(")");
			}
		}

		String result;
		if (hasPrivileges)
			result = (new StringBuilder(" ( ")).append(conditions.substring(3))
					.append(" ) ").toString();
		else
			result = " 1=2 ";
		sql = StringUtil.replace(sql, "${DP}", result);
		if (log.isDebugEnabled())
			log.debug((new StringBuilder("sql authorization: ")).append(sql)
					.toString());
		return sql;
	}

	private static final String getDpSql(Object dpNode, ActionContext ac) {
		if (dpNode instanceof SqlProvider)
			return ((SqlProvider) dpNode).getSql(ac);
		else
			return dpNode.toString();
	}

}
